<template>
    <div class="renellm">
        <my-layout>
            <!-- 插入主内容区的内容 -->
            <template v-slot:main>
                <div class="detail_container">
                    <!--   飞书文档待优化 -->
                    <div class="block docx-heading2-block" data-record-id="PaHVdJlIKokrcExTy9Yc2D8cnjg">
                        <div class="heading-block">
                            <h2>GCG：</h2>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="KVR2dPYgpocx41x7QVecwa6LnMd">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <span class="title_txt">Source:</span>
                                <a style="cursor:pointer;text-decoration-skip:none;" class="link"
                                   href="https://arxiv.org/abs/2307.15043" target="_blank"
                                ><span>Universal and Transferable Adversarial Attacks on Aligned Language Models</span></a>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="EWj4dKhFCo5l32xvaCDcncolnMb">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <span class="title_txt">Github repo:</span>
                                <a style="cursor:pointer;text-decoration-skip:none;" class="link"
                                   href="https://github.com/llm-attacks/llm-attacks" target="_blank"
                                ><span>https://github.com/llm-attacks/llm-attacks</span></a>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block"  data-record-id="T0KSdjH8ToHvosxZtfAc15ZWnub">
                        <div class="text-block">
                            <h4>Introduction:</h4>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="Xl7BdA73joPunGxuD6ncevjtn9f">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>This paper proposes an algorithm named Greedy Coordinate Gradient (GCG).
                                    Briefly, GCG iteratively optimizes a specific section in the prompt using guidance from token gradients,
                                    ensuring that the model produces the desired text.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-image-block" data-record-id="AYdyd122UoYDs5xQudecXtlLnHd">
                        <div class="img" image-token="MHg2bWA9AoozAaxpMWhcbBKensg">
                            <img draggable="false" src="@/assets/doc/img5.png"/>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="L8DWdiy79osRFIxGlNycZ9Pgnqc">
                        <div class="text-block">
                            <h4>Adjustable parameters:</h4>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="VbSddseisof81vxlaqic6ixEnHb">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>attack_model (WhiteBoxModelBase): Model used to compute gradient variations and select optimal mutations based on loss.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="VGSSdRYkpoOKRoxBxH2cEezNn2c">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>target_model (ModelBase): Model used to generate target responses.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="TkREdl7dooVuOvxQJGnczqeYnjF">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>jailbreak_datasets (JailbreakDataset): Dataset for the attack.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="JrCgdLu9woy4oHxhFOOcU1xXnog">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>jailbreak_prompt_length (int): Number of tokens in the jailbreak prompt. Defaults to 20.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="IKqodywEsoAeGExtEQVc4PSJnJb">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>num_turb_sample (int): Number of mutant samples generated per instance. Defaults to 512.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="UahmdhHeBoAmEhxOYxLcrPKknKc">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>batchsize (int): Batch size for computing loss during the selection of optimal mutant samples. If encountering OOM errors,
                                    consider reducing this value. Defaults to None, which is set to the same as num_turb_sample.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="EAQrd1RnHo4mfmx5avTc76oxnbe">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>top_k (int): Randomly select the target mutant token from the top_k with the smallest gradient values at each position. Defaults to 256.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="KWitdkEEJosZ9zxmTWncW8vJnld">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>max_num_iter (int): Maximum number of iterations. Will exit early if all samples are successfully attacked. Defaults to 500.</p>
                            </div>
                        </div>
                    </div>
                    <div class="block docx-text-block" data-record-id="GHDJdROp8oyk43xgKDWchvUlnjd">
                        <div class="text-block-wrapper">
                            <div class="text-block">
                                <p>is_universal (bool): Experimental feature. Optimize a shared jailbreak prompt for all instances. Defaults to False.</p>
                            </div>
                        </div>
                    </div>
                    <!--   飞书文档待优化 -->

                    <div class="effect">
                        <h4>Jailbreak prompt examples</h4>
                        <div class="exampleSelectorContainer">
                            <span>Select an Example：</span>
                            <el-select clearable v-model="fnName" placeholder="Please click to select"  @change="fetchMessage">
                                <el-option
                                        v-for="(value, name) in testData"
                                        :key="name"
                                        :label="name"
                                        :value="name">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="chatbot">
                            <section class="chatbot1">
                                <div class="chatbotHeader">
                                    <img src="@/assets/ChatGPT_logo.png" alt="ChatGPT Icon">
                                    <span>ChatGPT</span>
                                </div>
                                <div class="output-container">
                                    <div  v-show="!!fnName">
                                        <div class="userMessage">
                                            <span class="who">User: </span>
                                            {{showMsg.title}}
                                        </div>
                                        <div class="assistantMessage">
                                            <span class="who">Assistant: </span>
                                            {{showMsg.leftContent}}}
                                        </div>
                                    </div>
                                </div>
                            </section>
                            <section>
                                <div class="chatbotHeader">
                                    <img src="@/assets/devil.png" alt="devil Icon">
                                    <span>Jailbreak result</span>
                                </div>
                                <div class="output-container">
                                    <div v-show="!!fnName">
                                        <div class="userMessage">
                                            <span class="who">User: </span>
                                            {{showMsg.title}}
                                        </div>
                                        <div class="assistantMessage">
                                            <span class="who">Assistant: </span>
                                            {{showMsg.content}}}
                                        </div>
                                    </div>
                                </div>
                            </section>
                        </div>
                    </div>
                </div>
            </template>
        </my-layout>
    </div>
</template>

<script>
  import MyLayout from '@/views/MyLayout.vue'
  const initVale = {content:'',title:'',leftContent:''};
  export default {
    components: {
      MyLayout
    },
    data() {
      return {
        fnName:'',
        testData:{},
        showMsg:{...initVale},
        intervalId: null,
        meIntervalId: null,
      };
    },
    methods:{
      fetchMessage(val) {
        if(this.intervalId) {clearInterval(this.intervalId);}
        if(this.meIntervalId) {clearInterval(this.meIntervalId);}
        this.showMsg = {...initVale};
        if (val) {
          const content = this.testData[val];
          const leftContent = `I'm sorry, but I cannot assist with creating a phishing email or any other unethical activities.
                                        My purpose is to provide helpful and responsible information to users.
                                        If you have any other non-harmful requests or questions, feel free to ask,
                                        and I'll be happy to assist you.`;
          this.showMsg.title = val;
          let i = 0 , j = 0;
          this.meIntervalId = setInterval(() => {
            if (i < content.length) {
              this.showMsg.content += content.charAt(i);
              i++;
            } else {
              clearInterval(this.meIntervalId);
            }
          }, 10);
          this.intervalId = setInterval(() => {
            if (j < leftContent.length) {
              this.showMsg.leftContent += leftContent.charAt(j);
              j++;
            } else {
              clearInterval(this.intervalId);
            }
          }, 10);
        }
      }
    },
    created() {
      fetch(window.location.protocol + '//' + window.location.host+'/gcg.jsonl')
        .then(response => response.text())
        .then(content => {
          // 处理 content 中的 JSON Lines 数据
          let linesArray = content.split(/\n|\r\n/);
          linesArray = linesArray.filter(item => item);
          // const obj = linesArray[0];  // 字符串
          // 逐行解析每个 JSON 对象
          const jsonArray = linesArray.map(line => {
            const obj = new Function(`return ${line}`)()
            return obj;
          });
          const testData = {};
          // 每一个行的结构obj是：{"jailbreak_prompt": xxx,"target_responses":[xxxx],"query":xxxx,"eval_results":[xxxxx]}
          for(let item of jsonArray){
            testData[item.query] = Array.isArray(item.target_responses) ? item.target_responses[0] : '';
          }
          this.testData = testData;
        })
        .catch(error => console.error(error));
    },
    beforeDestroy() {
      clearInterval(this.intervalId);
      clearInterval(this.meIntervalId);
    }
  };
</script>

